<template>
  <div class="senior-setting-main">
    <Dialog ref="dialogRef" :state="dialogInfo" top="20vh" draggable @confirm="onSubmit" @cancel="onCancel" >
      <template #default>
        <div class="setting-box">
          <div class="desc">
            由于企业微信官方限制，当客户今日可接收群发消息已达上限，客户将不再收到群发消息。通过高级配置，便可主动获取已达上限的客户消息，执行私信发送。若想使用该功能，请联系我们的<span @click="toCustomerService">客服</span>协助开通使用！
          </div>
          <el-form ref="formDataRef" class="form-box" :rules="rules" :model="formData" label-width="126px">
            <div class="form-box-item">
              同步设置：
            </div>
            <el-form-item label="同步频率：" prop="SyncFrequencyVue">
              每<el-input-number v-model="formData.SyncFrequencyVue" :min="SyncFrequencyMinValue" class="num-input" :controls="false" :precision="0" placeholder="" />
              <el-select class="select-input" v-model="formData.SyncFrequencyType" placeholder="" @change="handleRequencyTypeChange('Sync')">
                <!-- // 同步设置的切换使用最小值默认值的 -->
                <el-option 
                  v-for="item in timeStatus" 
                  :key="item.code" 
                  :label="item.label" 
                  :value="item.code" />
              </el-select>
              同步一次。
              <div class="tip" >注意：最小频率为10秒</div>
            </el-form-item>
            <div class="form-box-item">
              群发设置：
            </div>
            <el-form-item label="群发执行频率：" prop="MassFrequencyValue">
              <el-input-number v-model="formData.MassFrequencyMinVue" :min="1" class="num-input" :controls="false" :precision="0" placeholder="" /> ～ 
              <el-input-number v-model="formData.MassFrequencyMaxVue" :min="1" class="num-input" :controls="false" :precision="0" placeholder="" />
              <el-select class="select-input" v-model="formData.MassFrequencyType" placeholder="" @change="handleRequencyTypeChange('Mass')">
                <el-option 
                  v-for="item in timeStatus" 
                  :key="item.code" 
                  :label="item.label" 
                  :value="item.code" />
              </el-select>
              执行一次。
            </el-form-item>
          </el-form>
        </div>
      </template>
    </Dialog>
    <el-dialog v-model="warningVisible" title="警告" width="418px" top="30vh" draggable >
      <div class="warning-info">
        <el-icon class="warning-icon" size="80px" color="red" ><WarnTriangleFilled /></el-icon>
        <div class="warning-desc">
          <span>您设置的最小执行频率少于1分钟，封号的风险会更大，点击确认后表示</span>
          <span class="error" >您愿意承担此操作带来的风险且立即生效</span>
          <span>，请慎重操作！！！</span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="warningVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitWarning">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts"> 
import { ref, reactive, watch, computed } from 'vue'
import Dialog from '@renderer/components/dialog'
import { advancedShow, advancedSet } from '@renderer/ajax/api/groupMonitor'
import { store } from '@renderer/store'
import { ElMessage } from 'element-plus'

const formDataRef = ref<any>(null)

const dialogInfo = reactive<any>({
  visible: false,
  width: '600px',
  title: '高级配置',
  footer: ['取消', '确定', 'right']
})

const formData = reactive<any>({
  AppKey: '',
  AppSecret: '',
  CorpId: '',
  MassFrequencyMaxVue: '',
  MassFrequencyMinVue: '',
  MassFrequencyType: 1,
  SyncFrequencyType: 1,
  SyncFrequencyVue: '',
  Token: '',
})

const valTowValue = (rule, value, callback) => {
  if(formData.MassFrequencyMinVue && formData.MassFrequencyMaxVue) {
    if (formData.MassFrequencyMinVue > formData.MassFrequencyMaxVue) {
      return callback(new Error('清输入正确的同步频率'))
    }
    callback()
  } else {
    callback(new Error('请填写群发执行频率 '))
  }
}

const rules = reactive<any>({

  SyncFrequencyVue: [
    { required: true, message: '请填写同步频率', trigger: 'blur' },
  ],
  MassFrequencyValue: [
    { required: true, validator: valTowValue, trigger: 'change' },
  ],
})

const SyncFrequencyMinValue = computed(() => {
  // 选择为秒的情况下最小值为10
  return formData.SyncFrequencyType === 4 ? 10 : 1
})

const defaultTimeMap = new Map([
  [1, { min: 3, max: 5 }], // 分钟默认值
  [2, { min: 1, max: 3 }], // 小时默认值
  [3, { min: 1, max: 7 }], // 天默认值
  [4, { min: 180, max: 300 }] // 秒默认值
])
const getDefaultByFrequencyType = () => {
  return {
    Sync: defaultTimeMap.get(formData.SyncFrequencyType), // 同步频率
    Mass: defaultTimeMap.get(formData.MassFrequencyType) // 群发频率
  }
}

const handleRequencyTypeChange = (type: string) => {
  const defaultValue = getDefaultByFrequencyType()[type]
  const adapterFrequency = {
    Sync: { min: 'SyncFrequencyVue', max: 'SyncFrequencyVue' },
    Mass: { min: 'MassFrequencyMinVue', max: 'MassFrequencyMaxVue' },
  }[type]

  formData[adapterFrequency.max] = defaultValue.max
  formData[adapterFrequency.min] = defaultValue.min
}

const timeStatus = reactive<any>([
  { label: '秒', code: 4 },
  { label: '分钟', code: 1 },
  { label: '小时', code: 2 },
  { label: '天', code: 3 }
])

const onCancel = () => {
  dialogInfo.visible = false
}

const handleAdvancedSet = async () => {
  await advancedSet({ ...formData })
  ElMessage.success('设置成功')
}
const onSubmit = async () => {
  formDataRef.value.validate(async (res) => {
    if(res) {
      let params = {
        ...formData
      }
      if (params.MassFrequencyMinVue < 60 && params.MassFrequencyType === 4) {
        warningVisible.value = true
      } else {
        await handleAdvancedSet()
        dialogInfo.visible = false
      }
    }
  })
}

// 警告弹窗
const warningVisible = ref(false)
const handleSubmitWarning = async () => {
  await handleAdvancedSet()
  warningVisible.value = false
  dialogInfo.visible = false
}


const toCustomerService = () => {

}

const getAdvancedShow = async () => {
  let info = store.getters['common/getUserInfo']
  let parasm = {
    CorpId: info.CorpID
  }
  formData.CorpId = info.CorpID
  let res: any = await advancedShow(parasm)
  Object.assign(formData, res)
  if(!formData.SyncFrequencyType) {
    formData.SyncFrequencyType = ''
  }
  if(!formData.MassFrequencyType) {
    formData.MassFrequencyType = ''
  }
  console.log(res,'123')
}

getAdvancedShow()

watch(dialogInfo.visible,(val) => {
  console.log(val,'val')
})

defineExpose({
  dialogInfo
})

</script>
<style lang="scss" scoped>
.senior-setting-main {
  .setting-box {
    .desc {
      padding: 12px 14px;
      line-height: 22px;
      background: rgba(24, 144, 255, 0.07);
      border: 1px solid rgb(64, 149, 229);
      border-radius: 2px;
      span {
        color: rgb(64, 149, 229);
        cursor: pointer;
      }
    }
    .form-box {
      margin: 16px 0;
      .form-box-item {

      }
      .num-input {
        margin: 0 6px;
        width: 68px;
      }
      .select-input {
        margin-right: 6px;
        width: 100px;
      }
    }
  }
}

.tip {
  font-size: 14px;
  color: #666;
}
.warning-info {
  display: flex;
  .warning-icon {
    margin-right: 10px;
  }
  .warning-desc {
    font-size: 16px;
    line-height: 22px;
  }
}

.error {
  color: red;
}
</style>